package com.myk.game.shapechesstool.utils;

import android.graphics.Bitmap;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * 截屏工具类
 */
public class ScreenShotUtil {

    /**
     * 用最上层活动的根View转Bitmap的方式截图
     */
    public static void shotByView(String filePath, Runnable successTask, Runnable failureTask) {
        new Thread(() -> {
            try {
                Bitmap bitmap = ScreenUtils.screenShot(ActivityUtils.getTopActivity());
                if (ImageUtils.save(bitmap, filePath, Bitmap.CompressFormat.JPEG)) {
                    successTask.run();
                }
                else {
                    failureTask.run();
                }
            }
            catch (Exception e) {
                LogUtils.e("视图截屏发生异常->" + e.toString());
                failureTask.run();
            }
        }).start();
    }

    /**
     * 用su命令行的方式截图
     */
    public static void shotByCmd(String filePath, Runnable successTask, Runnable failureTask) {
        new Thread(() -> {
            try {
                int result = -1;
                DataOutputStream dos = null;
                try {
                    Process p = Runtime.getRuntime().exec("su");
                    dos = new DataOutputStream(p.getOutputStream());
                    dos.writeBytes("screencap -p " + filePath + "\n");
                    dos.flush();
                    dos.writeBytes("exit\n");
                    dos.flush();
                    p.waitFor();
                    result = p.exitValue();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    if (dos != null) {
                        try {
                            dos.close();
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (result == -1) {
                    failureTask.run();
                }
                else {
                    successTask.run();
                }
            }
            catch (Exception e) {
                LogUtils.e("命令行执行发生异常->" + e.toString());
                failureTask.run();
            }
        }).start();
    }
}
